

package com.hazelcast.scheduledexecutor.impl;

import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicInteger;

public class MemberCapacityPermit implements CapacityPermit {

    private final String name;
    private final int capacity;
    private AtomicInteger permits;

    MemberCapacityPermit(String name, int permits) {
        this.name = name;
        this.capacity = permits;
        this.permits = new AtomicInteger(permits);
    }

    @Override
    public void acquire() throws RejectedExecutionException {
        if (permits.getAndDecrement() <= 0) {
            // Release that incr
            permits.incrementAndGet();

            throw new RejectedExecutionException("Maximum capacity (" + capacity + ") of tasks reached for this member " + "and scheduled executor (" + name + "). " + "Reminder, that tasks must be disposed if not needed.");

        }

    }

    @Override
    public void acquireQuietly() {
        permits.getAndDecrement();
    }

    @Override
    public void release() {
        permits.incrementAndGet();
    }

    @Override
    public int totalAcquired() {
        return capacity - permits.get();
    }
}
